<template>
  <div class="app-container">

    <!-- 过滤器 -->
    <div class="filter-container">
      <span>住院号: </span>
      <el-input
        v-model="listQuery.admission_no"
        placeholder="请输入住院号"
        style="width: 200px;"
        class="filter-item"
      />
      <!-- 空隙 -->
      <div style="width: 20px; display: inline-block;" />
      <span>身份证: </span>
      <el-input
        v-model="listQuery.identity_card"
        placeholder="请输入身份证"
        style="width: 200px;"
        class="filter-item"
      />
      <!-- 空隙 -->
      <div style="width: 20px; display: inline-block;" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <!-- 新增按钮 -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-plus" @click="openAddDialog">
        新增
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table v-loading="listLoading" :data="userinfo" border fit highlight-current-row style="width: 100%">
      <!-- ID -->
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <!-- 住院号 -->
      <el-table-column align="center" label="住院号" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.admission_no }}</span>
        </template>
      </el-table-column>
      <!-- 身份证号 -->
      <el-table-column align="center" label="身份证号" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.identity_card }}</span>
        </template>
      </el-table-column>
      <!-- 训练名称 -->
      <el-table-column align="center" label="训练名称" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.video_name }}</span>
        </template>
      </el-table-column>
      <!-- 评价 -->
      <el-table-column align="center" label="评价" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.rating }}</span>
        </template>
      </el-table-column>
      <!-- 训练次数 -->
      <el-table-column align="center" label="训练次数" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.num }}</span>
        </template>
      </el-table-column>
      <!-- 训练时间(单位:秒) -->
      <el-table-column align="center" label="训练时间(单位:秒)" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.train_time_sum }}</span>
        </template>
      </el-table-column>
      <!-- 评价时间 -->
      <el-table-column align="center" label="评价时间" width="120">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column align="center" label="操作" width="400" fixed="right">
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button v-waves type="primary" icon="el-icon-edit" @click="openEditDialog(scope.row)">
            编辑
          </el-button>
          <el-button v-waves type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 新增对话框 -->
    <el-dialog title="新增患者" :visible.sync="addDialogVisible">
      <el-form :model="addForm" label-width="120px">
	    <el-form-item label="住院号">
          <el-input v-model="addForm.admission_no" />
        </el-form-item>
        <el-form-item label="身份证号/用户唯一id">
          <el-input v-model="addForm.identity_card" />
        </el-form-item>
        <el-form-item label="训练名称">
          <el-input v-model="addForm.video_name" />
        </el-form-item>
        <el-form-item label="评价">
          <el-input v-model="addForm.rating" />
        </el-form-item>
        <el-form-item label="训练次数">
          <el-input v-model="addForm.num" />
        </el-form-item>
        <el-form-item label="训练时间(单位:秒)">
          <el-input v-model="addForm.train_time_sum" />
        </el-form-item>
      </el-form>
      <!-- 对话框底部的按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">保存</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑患者" :visible.sync="editDialogVisible">
      <el-form :model="editForm" label-width="120px">
		    <el-form-item label="住院号">
          <el-input v-model="editForm.admission_no" />
        </el-form-item>
        <el-form-item label="身份证号/用户唯一id">
          <el-input v-model="editForm.identity_card" />
        </el-form-item>
        <el-form-item label="训练名称">
          <el-input v-model="editForm.video_name" />
        </el-form-item>
        <el-form-item label="评价">
          <el-input v-model="editForm.rating" />
        </el-form-item>
        <el-form-item label="训练次数">
          <el-input v-model="editForm.num" />
        </el-form-item>
        <el-form-item label="训练时间(单位:秒)">
          <el-input v-model="editForm.train_time_sum" />
        </el-form-item>
      </el-form>
      <!-- 对话框底部的按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ratingsList } from '@/api/nurse/ratings_list' // 导入查询接口
import Pagination from '@/components/Pagination'
import { deleteRatings } from '@/api/nurse/ratings_list' // 导入删除接口
import { addRatings } from '@/api/nurse/ratings_list' // 导入新增接口
import { updateRatings } from '@/api/nurse/ratings_list' // 导入编辑接口

export default {
  name: 'ratingsList',
  components: { Pagination },
  data() {
    return {
      userinfo: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        admission_no: '', // 添加住院号搜索
        identity_card: '', // 添加姓名身份证
      },
      addDialogVisible: false, // 控制新增对话框的显示
      addForm: { // 新增表单
        admission_no: '',
        identity_card: '',
        video_name: '',
        rating: '',
        num: '',
        train_time_sum: ''
      },
      addForm: {
        // 新增页面字段初始化默认值
        // 其他字段
      },
      idd: {"id":1},
      editDialogVisible: false, // 控制编辑对话框的显示
      editForm: { // 编辑表单
        id: '',
        admission_no: '',
        identity_card: '',
        video_name: '',
        rating: '',
        num: '',
        train_time_sum: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      ratingsList(this.listQuery).then(response => {
        // 过滤数据，新增 group 条件
        const filteredData = response.data.userinfo.filter(item => {
          const admissionNoMatch = this.listQuery.admission_no === '' || item[7].includes(this.listQuery.admission_no)
          const nameMatch = this.listQuery.identity_card === '' || item[6].includes(this.listQuery.identity_card)
          return admissionNoMatch && nameMatch
        })

        // 确定当前页面的数据起始和结束索引
        const start = (this.listQuery.page - 1) * this.listQuery.limit
        const end = start + this.listQuery.limit

        // 使用 slice 截取当前页的数据
        const paginatedData = filteredData.slice(start, end)

        // 查看数据
        // 遍历 `paginatedData` 数组，构建每一行的数据
        this.userinfo = paginatedData.map(item => ({
		      id: item[0],
          video_name: item[1],
          rating: item[2],
          num: item[3],
          train_time_sum: item[4],
          create_time: item[5],
          identity_card: item[6],
          admission_no: item[7]
        }))

        // 设置 total 的值为过滤后的数据总数
        this.total = filteredData.length
        this.listLoading = false
      }).catch(error => {
        console.error('Failed to fetch data:', error)
        this.listLoading = false
      })
    },
    // 删除逻辑
    handleDelete(id) {
      console.log(id)
      this.$confirm('确定删除此条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
       let iddd ={"id":id}
        console.log(iddd)
        deleteRatings(iddd)
          .then(response => { 
            this.$message.success('删除成功!')
            this.getList() // 删除成功后刷新列表
          })
          .catch(error => {
            console.error('Failed to delete data:', error)
            this.$message.error('删除失败!')
          })
          .finally(() => {
            this.listLoading = false
          })
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 打开新增对话框
    openAddDialog() {
      console.log('新增按钮被点击了') // 检查点击事件
      this.addDialogVisible = true
    },
    // 保存新增数据
    handleAdd() {
      // 检查是否可以保存
      console.log('新增数据', this.addForm)

      // 发送新增请求
      addRatings(this.addForm).then(() => {
        this.$message.success('新增成功!')
        this.addDialogVisible = false // 关闭对话框
        this.getList() // 刷新列表
      }).catch(() => {
        this.$message.error('新增失败!')
      })
    },
    // 打开编辑对话框
    openEditDialog(row) {
      // 将选中行的数据填充到 editForm 中
      this.editForm = { ...row }
      this.editDialogVisible = true
    },
    // 更新患者信息
    handleEdit() {
      // 发送更新请求
      updateRatings(this.editForm).then(() => {
        this.$message.success('更新成功!')
        this.editDialogVisible = false // 关闭对话框
        this.getList() // 刷新列表
      }).catch(() => {
        this.$message.error('更新失败!')
      })
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}/${month}/${day}`
    },
    // 格式化日期
    formatDate(date) {
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
    }
  }
}
</script>
